package com.caac.core.dao.hibernate;

import java.util.List;

import com.caac.core.dao.UserDao;
import com.caac.core.dm.Menu;
import com.caac.core.dm.Role;
import com.caac.core.dm.User;

import org.springframework.orm.ObjectRetrievalFailureException;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright AgileCentury 2004</p>
 * <p>Company: AgileCentury</p>
 * @author <a href="mailto:project@agilecentury.com">Project Group</a>
 * @version 1.0
 */

public class UserDaoHibernate extends BaseDaoHibernate implements UserDao {
    public User getUserById(String id) {
        try {
            return (User) getHibernateTemplate().get(User.class, id);
        } catch (Exception e) {
            return null;
        }
    }

    public User getUserByUsername(String username) {
        List users = getHibernateTemplate().find(
                "from User u where u.username = ?", username);
        if (users == null || users.size() != 1) {
            throw new ObjectRetrievalFailureException(User.class, username);
        }
        return (User) users.get(0);
    }

    public List getUsersByBureauId(String bureauId) {
        return getHibernateTemplate().find("from User nu ");
    }

    public void saveUser(User user) {
        getHibernateTemplate().saveOrUpdate(user);
    }

    public Role getRoleById(String id) {
        Role role = (Role) getHibernateTemplate().get(Role.class, id);
        return role;
    }

    public List getAllRoles() {
        return getHibernateTemplate().find("from Role r order by r.id");
    }

    public void saveRole(Role role) {
        getHibernateTemplate().saveOrUpdate(role);
    }

    public List getMenusByUsername(String username) {
        return getHibernateTemplate().findByNamedQuery("userMenu.SQL", username);
    }

    public List getMenusByUsername(String username, String sysNo) {
        return getHibernateTemplate().findByNamedQuery("userMenu2.SQL",
                new String[] {username, sysNo});
    }

    public Menu getMenuByMenuCode(String menuCode) {
        return (Menu) getHibernateTemplate().find(
                "from Menu a where a.menuCode = ?",
                new Integer(menuCode)).get(0);
    }

    public void saveRoleMenu(String roleId, String menuCode) {
        this.execNoResultSql("insert into permission values('" + roleId + "'," +
                             menuCode + ")");
    }

    public List getAllMenus() {
        return getHibernateTemplate().find("from Menu a order By a.menuCode");
    }

    public List getPermissionsByRoleId(String roleId) {
        return getHibernateTemplate().findByNamedQuery("rolePermission.SQL",
                roleId);
    }
}
